package com.wangtianxiang.sxp.weixin.filter;

import com.alibaba.fastjson.JSON;
import com.wangtianxiang.sxp.cache.utils.RedisUtil;
import com.wangtianxiang.sxp.po.WxUser;
import com.wangtianxiang.sxp.common.domain.User;
import com.wangtianxiang.sxp.common.http.ResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisUtil redisUtil;


    @Value("${token.expirationMilliSeconds}")
    private long expirationMilliSeconds;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取header中的token信息
        String authToken = request.getHeader("Authorization");
        response.setCharacterEncoding("utf-8");
        if (StringUtils.isEmpty(authToken)){
            filterChain.doFilter(request,response);//token格式不正确
            return;
        }

        //获取redis中的token信息
        if (!redisUtil.hasKey(authToken)){
            //token 不存在 返回错误信息
            response.getWriter().write(JSON.toJSONString(ResponseEntity.setForNotLogin()));
            return;
        }

        //获取缓存中的信息(根据自己的业务进行拓展)
        String wxUserJson = (String) redisUtil.get(authToken);
        if (StringUtils.isEmpty(wxUserJson)){
            //用户信息不存在或转换错误，返回错误信息
            response.getWriter().write(JSON.toJSONString(ResponseEntity.setForNotLogin()));
            return;
        }

        WxUser wxUser = JSON.parseObject(wxUserJson,WxUser.class);
        //从tokenInfo中取出用户信息
        User user = new User();
        user.setId(wxUser.getOpenid());

        //更新token过期时间
        redisUtil.setKeyExpire(authToken,expirationMilliSeconds);
        //将信息交给security
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user,null,user.getAuthorities());
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }
}
